package com.tuzes.reservation.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuzes.reservation.biz.common.ReservationState;
import com.tuzes.reservation.biz.service.IReservationService;
import com.tuzes.reservation.biz.service.ITimeSpanService;
import com.tuzes.reservation.entity.entity.Reservation;
import com.tuzes.reservation.entity.entity.TimeSpan;
import com.tuzes.reservation.entity.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  预约控制器
 * </p>
 *
 * @author tuzes
 * @since 2023-07-09
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/reservation")
@Api(value = "预约", tags = "预约")
public class ReservationController {
    private final IReservationService reservationService;
    private final ITimeSpanService timeSpanService;
    @PostMapping("/add")
    @ApiOperation(value = "预约", notes = "预约")
    public Boolean add(@RequestBody List<Reservation> saveVOs){
        if (saveVOs.size()>3){
            //预约时间段最多三个
            return false;
        }
        List<Reservation> reservations = new ArrayList<>();
        String code = UUID.randomUUID().toString();
        for (Reservation saveVO : saveVOs) {
            saveVO.setCreatedTime(LocalDateTime.now());
            saveVO.setCode(code);
            saveVO.setState(ReservationState.WAITED);
            Boolean isLegal = check(saveVO);
            if (isLegal) {
                reservations.add(saveVO);
            }else {
                //check失败，返回false
                return false;
            }
        }
        return reservationService.saveBatch(reservations);
    }
    @GetMapping("/listByTime")
    @ApiOperation(value = "查看某日期的已预约时间段", notes = "查看某日期的预约时间")
    public List<String> listByTime(@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime time){
        //获取预约时间的年月日
        LocalDate day = time.toLocalDate();
        LocalDateTime star = day.atTime(0,0,0);
        LocalDateTime end = day.atTime(23,59,59);
        //获取该日期内所有预约
        List<Reservation> list = reservationService.list(Wrappers.<Reservation>query().between("date",star,end));
        Set<String> result = new HashSet<>();
        list.forEach(n->{
            TimeSpan timeSpan = timeSpanService.getByCode(n.getTimeSpan());
            result.addAll(JSONUtil.toList(timeSpan.getRelationCode(),String.class));
        });
        return new ArrayList<>(result);
    }
    /**
    ·* 检查预约的时间段是否已被预约
    ·*/
    public Boolean check(Reservation reservation){
        List<String> timeSpans =  listByTime(reservation.getDate());
        String timeSpanSave =  reservation.getTimeSpan();
        if (timeSpans.contains(timeSpanSave)){
                //已存在的时间段列表中包含将要保存的时间段，则时间段已占用
                return false;
        }
        return true;
    }
    @GetMapping("/confirm")
    @ApiOperation(value = "确定已预约时间", notes = "确定已预约时间")
    public Boolean confirm(@RequestBody Reservation reservation){
        //获取本次预约所有时间段
        List<Reservation> list = reservationService.list(Wrappers.<Reservation>query().eq("code",reservation.getCode()));
        List<Long> ids = list.stream().map(n->n.getId()).collect(Collectors.toList());
        ids.remove(reservation.getId());
        reservationService.removeBatchByIds(ids);
        reservation = reservationService.getById(reservation.getId());
        reservation.setState(ReservationState.FINISH);
        return reservationService.updateById(reservation);
    }

    @GetMapping("/myReservation")
    @ApiOperation(value = "查看某用户的预约", notes = "查看某用户的预约")
    public List<Reservation> myReservation(@RequestBody User user){
        //获取本次预约所有时间段
        List<Reservation> list = reservationService.list(Wrappers.<Reservation>query().eq("user_id",user.getId()));
        if (CollUtil.isNotEmpty(list)){
            list.forEach(n->{
                if (!checkTime(n.getDate())){
                    n.setState(ReservationState.FINISH);
                    reservationService.updateById(n);
                }
            });
        }
        return list;
    }


    /**
     ·* 检查时间是否过期
     ·*/
    public Boolean checkTime(LocalDateTime reservationTime){
        LocalDateTime current = LocalDateTime.now();
        Duration duration = Duration.between(current,reservationTime);
        //相差的天数
        long days = duration.toDays();
        if (days<0){
            return false;
        }
        return true;
    }

}
